from django.conf import settings
from django.shortcuts import render
from rest_framework_jwt.views import ObtainJSONWebToken
# Create your views here.
from rest_framework import request

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from itsdangerous import TimedJSONWebSignatureSerializer  as TJS
from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import merge_cart_cookie_to_redis
from users.models import User

from users.serializers import UserSerializers, UserDetailSerializer, UserEmailSerializer


# 判断用户是否存在
class UserNameCountView(APIView):
    def get(self, request, username):
        # 查询手机数量
        count = User.objects.filter(username=username).count()

        # 返回数据给前端
        data = {
            "username": username,
            "count": count
        }

        return Response(data)


# 判断手机号是否存在
class MobileCountView(APIView):
    def get(self, request, mobile):
        # 查询手机数量
        count = User.objects.filter(mobile=mobile).count()

        # 返回数据给前:端
        data = {
            "mobile": mobile,
            "count": count
        }

        return Response(data)


# 用户注册（通过序列化实现）
class UserView(CreateAPIView):
    # 指定一个序列化器
    serializer_class = UserSerializers


# 实现前端个人中心资料的显示
# class UserDetailView(APIView):
#     def get(self, request):
#         # 获取用户对象
#         user = request.user
#
#         # 序列化返回
#         ser = UserDetailSerializer(user)
#
#         return Response(ser.data)

# 个人用户中心
class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer

    def get_object(self):
        return self.request.user


# 邮箱保存/发送邮件
class UserEmailView(UpdateAPIView):
    serializer_class = UserEmailSerializer

    # 重写方法，指定返回的结果内容（获取验证后的数据）
    def get_object(self):
        return self.request.user


class EmailVerifyView(GenericAPIView):
    def get(self, request):
        # 获取前端数据token
        data = request.query_params.get('token', None)
        if data is None:
            return Response({"errors": "缺少token值"})

        # 解密
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(data)
        except:
            return Response({'errors': '无效token值'})

        username = data.get('username')

        # 查询用户
        user = User.objects.get(username=username)

        # 邮箱状态更新
        user.email_active = True
        user.save()

        ser = UserDetailSerializer(user)

        return Response(ser.data)





# 合并购物车
class UserAuthorizeView(ObtainJSONWebToken):
    """
    用户认证
    """

    def post(self, request, *args, **kwargs):
        # 调用父类的方法，获取drf jwt扩展默认的认证用户处理结果
        response = super().post(request, *args, **kwargs)

        # 仿照drf jwt扩展对于用户登录的认证方式，判断用户是否认证登录成功
        # 如果用户登录认证成功，则合并购物车
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            response = merge_cart_cookie_to_redis(request, user, response)

        return response
